import { Button, Form, Input, Result } from 'antd'
import  { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { ResetSignUp, signup, SignupPayload } from '../../store/actions/auth.actions';
import { AppState } from '../../store/reducers';
import { AuthState } from '../../store/reducers/auth.reducer';
import Layout from './Layout'

const FormList = [
    {
        name:'name',
        label: '昵称'
    },
    {
        name: 'password',
        label: '密码',
        
    },
    {
        name: 'email',
        label: '邮箱',
    },

];

const Signup = () => {
    const auth = useSelector<AppState, AuthState>(state => state.auth)
    const  dispatch = useDispatch();
    const onFinish = (value: SignupPayload) => {
        dispatch(signup(value))
    }
    const [form] = Form.useForm();
    useEffect(() => {
        if(auth.signup.loaded && auth.signup.success){
            // 1. 注册成功 清空表单
            form.resetFields();
        }
       
    }, [auth, form])


    // 2. 注册成功 显示成功的提示信息
    const successMessage = () => {
        if(auth.signup.loaded && auth.signup.success){
            // 1. 注册成功 清空表单
            return (
                <Result
                    status="success"
                    title="注册成功"
                    extra={[
                    <Button type="primary" key="signin">
                        <Link to="/signin"> 登录 </Link>
                    </Button>
                    ]}
                />
            )
        }
        return false;
    }
    // 3. 注册失败 显示失败的提示信息

    const failMessage = () => {
        if(auth.signup.loaded && !auth.signup.success){
            // 1. 注册成功 清空表单
            return (
                <Result
                    status="warning"
                    title="注册失败"
                    subTitle={auth.signup.message}
                />
            )
        }
        return false;
    }

    useEffect(() => {
        return () => {
            // 4. 离开页面之前 重置状态
            dispatch(ResetSignUp())
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
    return (
        <Layout title="注册" subTitle="">
            {
                successMessage()
            }
            {
                failMessage()
            }
            <Form onFinish={onFinish} form={form}>
                {
                    FormList.map(item=>(
                        <Form.Item {...item} key={item.name}>
                            {
                                item.name === 'password' ? <Input.Password /> : <Input />
                            }
                        </Form.Item>
                    ))
                   
                }
                 <Form.Item >
                    <Button type="primary" htmlType="submit">
                        注册
                    </Button>
                </Form.Item>
            </Form>
        </Layout>
    )
}

export default Signup
